package mchecca.view;

import java.awt.Canvas;
import java.awt.Graphics;

import javax.swing.JPanel;
import javax.swing.JTextField;

import mchecca.controller.ChoiceController;
import mchecca.model.DecisionLinesEvent;
import mchecca.model.Edge;
import mchecca.model.Line;

/**
 * Canvas object for drawing Lines.
 * <p>
 * This specialized {@link Canvas} object does the following
 * <ul>
 * 	<li>Creating {@link JTextField}s and placing them in the decisions {@link JPanel}</li>
 * 	<li>Drawing the lines for the {@link DecisionLinesEvent}</li>
 * 	<li>Drawing all edges for each {@link Line}</li>
 * </ul>
 * @author Michael Checca
 */
public class LinesCanvas extends Canvas {
	/** Serialized version UID for DecisionLinesForm */
	private static final long serialVersionUID = -3807526553879289906L;
	/** DecisionLinesForm to update */
	DecisionLinesForm dlForm;
	/** DecisionLinesEvent to update */
	DecisionLinesEvent dlEvent;
	/** X location of the lines */
	int[] linesX;
	/** Determines if the paint method has been called for the first time */
	private boolean initialPaint;

	/**
	 * Create a new LinesCanvas.
	 * <p>
	 * Create drawing canvas necessary for the {@link DecisionLinesEvent}.
	 * @param dlEvent {@link DecisionLinesEvent} to draw for
	 */
	public LinesCanvas(DecisionLinesForm dlForm, DecisionLinesEvent dlEvent) {
		super();
		this.dlForm = dlForm;
		this.dlEvent = dlEvent;
		this.linesX = new int[dlEvent.getNumChoices()];
		this.initialPaint = true;
	}

	/**
	 * Overriden paint method for this {@link LinesCanvas}.
	 * <p>
	 * This paint method is responsible for doing the following
	 * <ul>
	 * 	<li>Initially creating the {@link JTextField}s for the choices</li>
	 * 	<li>Drawing all {@link Line}s in the {@link DecisionLinesEvent}</li>
	 * 	<li>Drawing every {@link Edge} in every {@link Line}</li>
	 * </ul>
	 */
	@Override
	public void paint(Graphics g) {
		JPanel pnlChoices = dlForm.pnlChoices;
		pnlChoices.setLayout(null);
		int txtWidth = 100;
		int y1 = 5, y2 = getHeight() - y1;
		int space = getWidth() / dlEvent.getNumChoices();
		int offset = space / 2;
		for (int i = 0; i < dlEvent.getNumChoices(); i++) {
			int x = offset + space * i;
			linesX[i] = x;
			if (initialPaint) {
				JTextField txtChoice = new JTextField();
				txtChoice.addActionListener(new ChoiceController(i, dlForm, dlEvent));
				txtChoice.setBounds(x - (txtWidth / 2), 5, txtWidth, 20);
				pnlChoices.add(String.format("choice_%d", i + 1), txtChoice);
			}
			g.drawLine(x, y1, x, y2);
		}
		for (Line l : dlEvent.getLines())
			for (Edge e : l.getEdges())
				g.drawLine(linesX[e.getLeft()], e.getHeight(), linesX[e.getRight()], e.getHeight());
		pnlChoices.repaint();
		initialPaint = false;
	}
}
